#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"

/*队列*/

typedef struct A_STRUCT
{
    char id;
    char data;
} xStruct;

void sendTask(void *pvParameters)
{
    // 队列句柄
    QueueHandle_t QHandle;
    QHandle = (QueueHandle_t)pvParameters;

    // 发送状态
    BaseType_t xStatus;
    // 发送的数据
    // char i = 0;
    // 发送的结构体
    // xStruct xUSB = {1, 55};
    // 发送指针
    char *pStrToSend;
    int i = 0;

    while (1)
    {
        // 动态分配内存
        pStrToSend = (char *)malloc(50);
        // 发送地址的方式
        snprintf(pStrToSend, 50, "today is a good day! %d\r\n", i);
        i++;
        // xStatus = xQueueSend(QHandle, &xUSB, 0);
        xStatus = xQueueSend(QHandle, &pStrToSend, 0); // 注意这里传入的还是指针地址
        if (xStatus == pdPASS)
        {
            // 成功发送
            printf("sendTask: %d\n", i);
        }
        else
        {
            // 发送失败
            printf("sendTask: failed\n");
        }
        // xUSB.id++;
        // xUSB.data++;

        vTaskDelay(pdMS_TO_TICKS(3000));
    }
}

void recvTask(void *pvParameters)
{
    QueueHandle_t QHandle;
    QHandle = (QueueHandle_t)pvParameters;

    BaseType_t xStatus;
    // char i = 0;
    // 接收的结构体
    // xStruct xUSB = {0, 0};
    char *pStrToRecv;

    while (1)
    {
        if (uxQueueMessagesWaiting(QHandle) != 0)
        // 是否有消息在等待
        {
            xStatus = xQueueReceive(QHandle, &pStrToRecv, 0);
            if (xStatus == pdPASS)
            {
                // 成功接收
                // printf("recvTask: id=%d; data=%d\n", xUSB.id, xUSB.data);
                printf("recvTask: %s\n", pStrToRecv);
            }
            else
            {
                // 接收失败
                printf("recvTask: failed\n");
            }
            // 释放内存，防止内存泄漏
            // 这里需要放到recvTask里面释放，因为如果在sendTask中释放，那recvTask就接收不到对应的地址
            free(pStrToRecv);
        }
        else
        {
            // 队列空
            printf("recvTask: queue is empty\n");
        }

        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

void app_main(void)
{
    QueueHandle_t QHandle;

    // QHandle = xQueueCreate(5, sizeof(xStruct));
    QHandle = xQueueCreate(5, sizeof(char *));
    if (QHandle != NULL)
    {
        printf("QHandle is not NULL\n");
        xTaskCreate(sendTask, "sendTask", 2048, (void *)QHandle, 5, NULL);
        xTaskCreate(recvTask, "recvTask", 2048, (void *)QHandle, 5, NULL);
    }
    else
    {
        printf("QHandle is NULL\n");
    }
}
